package com.ruoyi.system.service.impl;

import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.controller.SysUserxqController;
import com.ruoyi.system.controller.UserScoreController;
import com.ruoyi.system.domain.Evaluation;
import com.ruoyi.system.mapper.EvaluationMapper;
import com.ruoyi.system.service.EvaluationService;
import com.ruoyi.system.service.IUserScoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;


@Service
public class EvaluationServiceImpl implements EvaluationService {
    @Autowired
    private UserScoreController userScoreController;
    @Autowired
    private EvaluationMapper evaluationMapper;
    @Autowired
    private IUserScoreService userScoreService;
    @Autowired
    private EvaluationService evaluationService;
    @Autowired
    private SysUserxqController sysUserController;

    @Override
    public void updateorinsert(Evaluation evaluation) {
        String[] split = evaluation.getEvaluationDate().split("-");
        if (split.length>0){
            evaluation.setYear(split[0]);
        }
        if(split.length>1){
            evaluation.setMonth(split[1]);
            evaluation.setEvaluationDate(evaluation.getEvaluationDate()+"-"+01);
        }
        Evaluation evaluation1 = evaluationMapper.SelectOne01(evaluation);
        if (evaluation1 != null && evaluation1.getId() != null) {
            evaluationMapper.update(evaluation);
        } else {
            evaluationMapper.inssert(evaluation);
        }
    }

    @Override
    public Evaluation selectOne01(Evaluation evaluation) {
        Evaluation evaluation1=new Evaluation();
        System.out.println(evaluation.getQuarter());
        String quarter = evaluation.getQuarter();
        if(quarter.equals("null")){
            String[] split = evaluation.getEvaluationDate().split("-");
            if (split.length>0){
                evaluation.setYear(split[0]);
            }
            if(evaluation.getQuarter()==null){
                if(split.length>1){
                    evaluation.setMonth(split[1]);
                }
                if (split.length==2){
                    evaluation.setEvaluationDate(evaluation.getEvaluationDate()+"-"+01);
                }
            } evaluation1 = evaluationMapper.SelectOne01(evaluation);
        }else {
            evaluation1.setEvaluationDate(null);
            Map map = evaluationMapper.SelectOne02(evaluation);
            System.out.println(map);
            if(map!=null){
                evaluation1.setAbilityDimension(Double.valueOf(map.get("ability").toString()));
                evaluation1.setQualityDimension(Double.valueOf(map.get("quality").toString()));
                evaluation1.setTotalScore(Double.valueOf(map.get("total").toString()));
            }
        }
        return evaluation1;
    }

    @Override
    public List<Map<String, Object>> selectList(Map<String, Object> map) {
        return evaluationMapper.SelectByids(map);
    }

    @Override
    public List<Map<String, Object>> paiming(Map map) {
        {
            List<Map<String, Object>> data = new ArrayList<>();
            // 从请求参数中获取用户ID
            Long userId1 = SecurityUtils.getUserId();


            Map userRoleDept = userScoreService.selectUserIdgaoceng(userId1);

            System.out.println(userRoleDept);
            String roleId = null;
            String deptId = null;
            // 检查用户角色和部门信息是否存在
            if (userRoleDept == null) {
                Map add = new HashMap();
                add.put("code","用户信息不存在");
                data.add(add);
                return data;
            }
            roleId = String.valueOf(userRoleDept.get("role_id"));
            deptId = String.valueOf(userRoleDept.get("dept_id"));


            // 检查角色ID和部门ID是否完整
            if (roleId == null || deptId == null) {
                // 如果信息不完整，记录警告日志并返回错误信息
                Map add = new HashMap();
                add.put("code","用户角色或部门信息不完整");
                data.add(add);
            }
            // 开始获取具有相同角色和部门的用户列表
            List<Map> users = userScoreService.selectBylist(roleId, deptId);
            // 提取用户列表中的所有用户ID
            List<Long> userIds = users.stream().map(x -> (Long) x.get("user_id")).collect(Collectors.toList());
            String time = String.valueOf(map.get("time"));
            //截取时间
            String[] split = time.split("-");
            String year = null;
            String month = null;
            //定义查询
            if (split.length > 0) {
                year = split[0];
            }
            if (split.length > 1) {
                month = split[1];
            }
            // 遍历每个用户ID，获取用户详细信息
            if (userIds.size() > 0) {
                map.put("userids", userIds);
                map.put("year", year);
                map.put("month", month);
                List<Long> bao = new ArrayList<>();
                //获取评分
                List<Map> list = evaluationService.selectList(map);
                if (list.size() == 0) {
                    return null;
                }

                for (Map map1 : list) {
                    Long getuserid = Long.valueOf(String.valueOf(map1.get("user_id")));
                    for (Long uid : userIds) {
                        if (uid.equals(getuserid)) {
                            data.add(map1);
                            bao.add(uid);
                        }
                    }
                }
                //去重
                List<Long> sheng = Stream.concat(
                        userIds.stream().filter(e -> !bao.contains(e)),
                        bao.stream().filter(e -> !userIds.contains(e))
                ).collect(Collectors.toList());
                //获取身份
                if (sheng.size() > 0) {
                    List<Map> maps = userScoreService.selectUserId(sheng);
                    for (Map map1 : maps) {
                        map1.put("quality", 0.0);
                        map1.put("ability", 0.0);
                        map1.put("total", 0.0);
                        data.add(map1);
                    }
                }
            }
            // 返回包含评分数据的成功响应
            return data;
        }
    }

    @Override
    public Evaluation pingfeng(Map map) {Double p1 = 0.0;
        Double p2 = 0.0;
        Double totalscore = 0.0;
        Long l = Long.valueOf(String.valueOf(map.get("userId")));
        Evaluation evaluation = new Evaluation();
        if (l != null) {
            Map userRoleDept = userScoreService.selectUserIdgaoceng(l);
            String s = String.valueOf(userRoleDept.get("role_id"));
            String time = String.valueOf(map.get("time"));
            String[] split = time.split("-");
            String year = "";
            String month = "";
            if (split.length > 0) {
                year = split[0];
                evaluation.setYear(split[0]);
            }
            if (split.length > 1) {
                month = split[1];
                evaluation.setMonth(split[1]);
            }
            //计算分数
            List<Double> doubles1 = new ArrayList<>();
            if (s.equals("100")) {
                // 查询基础员工
//                System.out.println(map);
                Integer i = Integer.valueOf(month);
                if (i >= 1 && i <= 3) {
                    map.put("quarter", 1);
                } else if (i >= 4 && i <= 6) {
                    map.put("quarter", 2);
                } else if (i >= 7 && i <= 9) {
                    map.put("quarter", 3);
                } else if (i >= 10 && i <= 12) {
                    map.put("quarter", 4);
                } else {
                    map.put("quarter", 0);
                }
                evaluation.setYear(split[0]);
                doubles1 = userScoreController.selectuserscore(map);
            } else {
                Double p3 = 0.0;
                Double p4 = 0.0;
                Map mapp=new HashMap<>();
                //查询中层评分
                mapp.put("year", year);
                mapp.put("month", month);
                mapp.put("userId", l);
                mapp.put("parentId", 1);
                mapp.put("quarter", null);
                List<Map> selectcha = sysUserController.selectcha(mapp);
                for (Map pp:selectcha){
                    p3+=Double.valueOf(pp.get("score").toString());
                }
                mapp.put("parentId", 7);
                List<Map> selectcha01 = sysUserController.selectcha(mapp);
                for (Map pp:selectcha01){
                    p4+=Double.valueOf(pp.get("score").toString());
                }
                doubles1.add(p3);
                doubles1.add(p4);
            }

            // 将 p1 和 p2 四舍五入到两位小数
            if (doubles1.size() > 0) {
                p1 = new BigDecimal(doubles1.get(0)).setScale(2, RoundingMode.HALF_UP).doubleValue();
            }
            if (doubles1.size() > 1) {
                p2 = new BigDecimal(doubles1.get(1)).setScale(2, RoundingMode.HALF_UP).doubleValue();
            }
            // 创建一个列表用于存储最终结果
            totalscore = new BigDecimal(p1).add(new BigDecimal(p2)).setScale(2, RoundingMode.HALF_UP).doubleValue();
            // 创建一个Evaluation对象，添加或修改s
            if (p2 != 0.0 || p1 != 0.0) {
                evaluation.setUserId(l);
                evaluation.setQualityDimension(p1.doubleValue());
                evaluation.setAbilityDimension(p2.doubleValue());
                evaluation.setTotalScore(totalscore.doubleValue());
                evaluation.setEvaluationDate(time);
                evaluationService.updateorinsert(evaluation);
                evaluation=null;
            }
        }
        return evaluation;
    }

    @Override
    public Boolean pingfengweihu() {
        //定义维护人的id
        Integer uid = 1;
        Map userRoleDept = userScoreService.selectUserIdgaoceng(Long.valueOf(uid));
        System.out.println(userRoleDept);
        String roleId = null;
        String deptId = null;
        // 检查用户角色和部门信息是否存在
        if (userRoleDept == null) {
            return false;
        }
        //查询部门以及角色相关uid
        roleId = String.valueOf(userRoleDept.get("role_id"));
        deptId = String.valueOf(userRoleDept.get("dept_id"));
        List<Map> users = userScoreService.selectBylist(roleId, deptId);
        List<Long> userIds = users.stream().map(x -> (Long) x.get("user_id")).collect(Collectors.toList());
        //获取当前时间格式为年月
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
        String currentTime = now.format(formatter);
        //循环维护相关uid
        Map map = new HashMap<>();
        for (Long userId : userIds) {
            map.put("userId", userId);
            map.put("time", currentTime);
            pingfeng(map);
        }
        return true;
    }

}
